﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;

namespace maskx.JqGridHelper
{
    public class JSONHelper
    {
        public static StringBuilder WriteRowJsonWithColName(string idcol, SqlDataReader reader)
        {
            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                using (JsonWriter jw = new JsonTextWriter(sw))
                {
                    JsonSerializer ser = new JsonSerializer();
                    jw.WriteStartObject();
                    jw.WritePropertyName("rows");
                    jw.WriteStartArray();
                    while (reader.Read())
                    {
                        jw.WriteStartObject();
                        jw.WritePropertyName("id");
                        ser.Serialize(jw, reader[idcol]);

                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            jw.WritePropertyName(reader.GetName(i));
                            ser.Serialize(jw, reader[i]);
                        }

                        jw.WriteEndObject();
                    }
                    jw.WriteEndArray();
                    jw.WriteEndObject();
                }
            }
            return sb;
        }
    }
}